package top.healthylife.gateway.platform.lexin.api.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import top.healthylife.basics.utils.exception.BusinessException;
import top.healthylife.basics.utils.utils.SystemThreadLocal;
import top.healthylife.gateway.core.util.SystemConfigUtils;
import top.healthylife.gateway.dto.request.req.ApiReqDto;
import top.healthylife.gateway.platform.lexin.api.config.SetMealNo;
import top.healthylife.gateway.platform.lexin.api.config.SystemConfig;
import top.healthylife.gateway.platform.lexin.dto.basereq.LeXinUnifyReqDto;
import top.healthylife.gateway.platform.lexin.dto.baseres.LeXinUnifyResItemDto;
import top.heathylife.gateway.common.po.RecordRequestInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author : GaoZeXi
 * @date 2021/7/14 17:50
 */
@Slf4j
public class LeXinHttpUtil {

    static final String URL = "https://lechfin.api.fenqile.com/route0004/risk/queryData.json";

    static final String SUCCESS = "0";
    static final String NO_DATA = "12980001";

    static Map<String, Object> respCodeMap = new HashMap<>();

    static {
        respCodeMap.put("0", "请求成功");
        respCodeMap.put("12980001", "未查得");
        respCodeMap.put("12981001", "无效参数");
        respCodeMap.put("12981002", "权限不足");
        respCodeMap.put("12982002", "商户停用");
        respCodeMap.put("12982003", "商户试用结束");
        respCodeMap.put("12982004", "IP地址异常");
        respCodeMap.put("12983001", "不在有效时间范围内");
        respCodeMap.put("12983002", "免费次数用尽");
        respCodeMap.put("12983003", "解密失败");
        respCodeMap.put("12983004", "服务未配置接口");
        respCodeMap.put("12983099", "业务异常");
        respCodeMap.put("10200001", "服务异常");
        respCodeMap.put("10200002", "参数不存在");
        respCodeMap.put("10200003", "未知的异常");
        respCodeMap.put("10200004", "url不存在");
        respCodeMap.put("10200005", "用户未登录");
        respCodeMap.put("10200006", "未找对服务");
        respCodeMap.put("10200007", "参数不合法");
        respCodeMap.put("10200008", "登录态被剔除");
        respCodeMap.put("10200009", "签名验证失败");
        respCodeMap.put("10200010", "异常默认错误");
        respCodeMap.put("10200011", "URL最大长度限制");
        respCodeMap.put("10200012", "消息推送失败");
        respCodeMap.put("10200013", "未找到对应的APP数据");
        respCodeMap.put("10200014", "参数不合法");
        respCodeMap.put("10200015", "请求时间差超过范围");
        respCodeMap.put("10200016", "session服务繁忙");
        respCodeMap.put("10200017", "解密失败");
        respCodeMap.put("10200018", "加密失败");
        respCodeMap.put("10201111", "无效的appKey");
    }

    /**
     * 请求接口
     *
     * @param apiReqDto 入参
     * @return T 出参对象
     */
    @SneakyThrows
    public static <T> T HttpRequest(ApiReqDto apiReqDto, String apiName, Class<T> clz) {
        LeXinUnifyReqDto reqDto = (LeXinUnifyReqDto) apiReqDto;
        //获取账号配置信息
        SystemConfig systemConfig = systemConfigInfo(reqDto);
        /*应用Key*/
        String appKey = systemConfig.getAppKey();
        /*签名密钥*/
        String appSecret = systemConfig.getAppSecret();
        /*RSA加密公钥*/
        String pubKey = systemConfig.getPublicKey();
        //构建通用参数
        BusinessParam businessParam = buildBusinessParam(systemConfig, apiName);
        //构建业务参数
        ElementParam elementParam = buildElementParam(reqDto);
        //客户端请求参数 用来请求接口准备参数信息
        ClientParam clientParam = new ClientParam();
        clientParam.setAppKey(appKey);
        clientParam.setAppSecret(appSecret);
        clientParam.setPubKey(pubKey);
        clientParam.setUrl(URL);
        clientParam.setBusinessParam(businessParam);
        clientParam.setElementParam(elementParam);

        //乐信请求客户端
        LexinClient client = new LexinRequestClient();
        //默认请求方法
        try {
            RecordRequestInfo.recordRequest(URL+"(使用lexinSDK发送)", JSONObject.toJSONString(clientParam), null, "post");
            BusinessRes<LeXinUnifyResItemDto> businessRes = client.defaultInvoke(clientParam);
            String code = businessRes.getCode();
            log.info("乐信接口返回:{}", JSONObject.toJSONString(businessRes));
            //将三方元数据存储到线程变量
            SystemThreadLocal.set(ORIGIN_DATA, JSONObject.toJSONString(businessRes));
            if (SUCCESS.equals(code)) {
                String json = JSONObject.toJSONString(businessRes.getData());
                JSONObject jsonObject = JSONObject.parseObject(json);
                jsonObject.put("traceId", businessRes.getTraceId());
                //是否计费,不返回给下游
                log.info("本次调用是否计费:{}", businessRes.getIsCost());
                return jsonObject.toJavaObject(clz);
            }
            if (NO_DATA.equals(code)) {
                return clz.newInstance();
            }
            if (respCodeMap.containsKey(code)) {
                Object exception = respCodeMap.get(code);
                log.error("接口正常调用,乐信服务返回的异常,异常信息:{}", exception);
                throw new BusinessException("乐信返回:{}", exception);
            }
        } catch (Exception e) {
            String msg = e.getMessage();
            if (e.getMessage().equals("乐信数据接口调用异常")) {
                msg = msg + e.getCause();
            }
            throw new BusinessException("接口请求异常,异常信息:{}", msg);
        }
        return clz.newInstance();
    }

    private static BusinessParam buildBusinessParam(SystemConfig systemConfig, String apiName) {
        /*接口授权Key*/
        String apiKey = systemConfig.getApiKey();
        /*业务套餐号*/
        List<SetMealNo> setMealNos = systemConfig.getSetMealNos();
        SetMealNo setMealNo = setMealNos.stream().filter(e -> e.getApiName().equals(apiName)).findFirst()
                .orElseThrow(() -> new BusinessException("该账号尚未配置该产品套餐号"));
        /*业务参数*/
        BusinessParam businessParam = new BusinessParam();
        /*接口授权Key*/
        businessParam.setApiKey(apiKey);
        /*商户ID 非必填*/
        String merchantId = systemConfig.getMerchantId();
        if (ObjectUtil.isNotEmpty(merchantId)) {
            businessParam.setMerchantId(merchantId);
        }
        /*业务ID  非必填*/
        String businessId = systemConfig.getBusinessId();
        if (ObjectUtil.isNotEmpty(businessId)) {
            businessParam.setBusinessId(businessId);
        }

        /*三/四要素加密类型 支持明文、MD5 和 SHA-256 加密方式，不传默认明文，注意：有的业务只支持明文方式，详见 EncTypeEnum*/
        businessParam.setEncType(systemConfig.getEncType().getType());
        /*业务套餐号*/
        businessParam.setSetMealNo(setMealNo.getSetMealNo());
        return businessParam;
    }

    private static ElementParam buildElementParam(LeXinUnifyReqDto reqDto) {
        //三/四要素信息
        ElementParam elementParam = new ElementParam();
        /*身份证姓名*/
        elementParam.setName(reqDto.getName());
        /*身份证号*/
        elementParam.setIdCard(reqDto.getIdCard());
        /*手机号*/
        elementParam.setPhone(reqDto.getPhone());
        /*银行卡号*/
        elementParam.setBankCard(reqDto.getBankCard());
        return elementParam;
    }

    /**
     * 访问日志输出和配置获取
     *
     * @param apiReqDto 入参
     * @return 账号信息
     */
    public static SystemConfig systemConfigInfo(ApiReqDto apiReqDto) {
        //可直接通过工具类获取这个对象
        SystemConfig o = (SystemConfig) SystemConfigUtils.get();
        log.info("请求参数为:{}", JSONObject.toJSONString(apiReqDto));
        log.info("账号信息为:{}", JSONObject.toJSONString(o));
        return o;
    }

}
